package com.fishing.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import QL.ButlerMailSendRequest;
import QL.ButlerMailSendResponse;
import QL.QLClient;
import net.sf.json.JSONArray;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fishing.entity.EmailSend;
import com.fishing.entity.L_Email;
import com.fishing.service.L_EmailService;
import com.fishing.util.ChangePropName;
import com.fishing.util.DateUtil;
import com.fishing.util.personal.GetItemConfig;
import com.fishing.util.personal.RemoveNullKeyValue;
/***
 *
 */
@Controller
public class EmailController{
	private static QLClient client = new QLClient();
	
	@Autowired
	private L_EmailService l_emailService;//初始化
	
	@RequestMapping("email/toList")
	public ModelAndView toList(HttpServletRequest request)throws Exception{
		
		ModelAndView mav = new ModelAndView("email/list");
		return mav;
	}
	
	@RequestMapping("email/toSimpleList")
	public ModelAndView toSimpleList(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("email/list_simple");
		return mav;
	}
	
	
	@RequestMapping("email/toAdd")
	public ModelAndView toAdd(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("email/add");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value="email/list",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map list(HttpServletRequest request,String PageIndex,String PageCount)throws Exception{
		List<?> email = this.l_emailService.selectAll(PageIndex,PageCount,(int)request.getSession().getAttribute("ZoneId"));
	    int count = this.l_emailService.selectCount((int)request.getSession().getAttribute("ZoneId"));
		/*List<L_Email> emailList = new ArrayList<L_Email>();
		//接收分页数据
		emailList = (List<L_Email>)email.get(0);
		System.out.println(emailList);
		//接收count数据
		L_Email count = ((List<L_Email>)email.get(1)).get(0);
		System.out.println(count);*/
		Map map = new HashMap();
		map.put("status", "200");
		map.put("message", "");
		map.put("count", count);
		map.put("data", email);
        JSONObject json = new JSONObject(map);
		return map;
	}
	
	
	@ResponseBody
	@RequestMapping(value="email/add",method = RequestMethod.POST,produces="text/html;charset=UTF-8") //防止页面乱码
	public String list(String formdata,HttpServletRequest request)throws Exception{ 
		EmailSend email = JSON.parseObject(formdata,EmailSend.class);
		ButlerMailSendRequest req = new ButlerMailSendRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		//req.SendType=1;
		//req.ReceiverId=0;
		if(email.getUserid().equals("全部玩家")) {
			req.SendType=1;
		}else {
			req.SendType=2;
			req.ReceiverId=Integer.parseInt((email.getUserid()));
		}
		req.Title=email.getTitle();
		req.Content=email.getContent();
		req.ValidationTime=Integer.parseInt((email.getTimeDiv()));
		HashMap<String, String> mapOld = new HashMap<String, String>();
		mapOld.put("WaterproofWood", email.getWaterproofWood());
		mapOld.put("RefinedOre",email.getRefinedOre());
		mapOld.put("TidalQuintessence",email.getTidalQuintessence());
		mapOld.put("SirenShell", email.getSirenShell());
		mapOld.put("Diamond", email.getDiamond());
		mapOld.put("Frozen", email.getFrozen());
		mapOld.put("Gold", email.getGold());
		mapOld.put("DeepSeaMagic", email.getDeepSeaMagic());
		mapOld.put("SplitCard", email.getSplitCard());
		mapOld.put("SummonGourd", email.getSummonGourd());
		mapOld.put("ViolentCard", email.getViolentCard());
		mapOld.put("Locking", email.getLocking());
		mapOld.put("Doublehit", email.getDoublehit());
		mapOld.put("Hammerfragment", email.getHammerfragment());
		mapOld.put("BronzeWarhead", email.getBronzeWarhead());
		mapOld.put("SilverWarhead", email.getSilverWarhead());
		mapOld.put("GoldWarhead", email.getGoldWarhead());
		mapOld.put("PlatinumWarhead", email.getPlatinumWarhead());
		RemoveNullKeyValue.removeNullValue(mapOld);
		
		StringBuilder sb = new StringBuilder();		
		Iterator<Map.Entry<String, String>> it = mapOld.entrySet().iterator(); //得这个集合的迭代器，保存在it里面
    	while (it.hasNext())//迭代具有更多元素，返回true
    	{
    		Entry<String, String> entry = it.next(); //返回迭代的下一个元素
    		if(!entry.getValue().equals("0")) {
    			String itemConfig = GetItemConfig.GetItemConfigString(entry.getKey());
    			if (!StringUtils.isEmpty(itemConfig))
    			{
    				if (sb.length() == 0)
    					sb.append('[');
    				else
    					sb.append(',');
    				sb.append('[');
    				sb.append(itemConfig);
    				sb.append(',');
    				sb.append(entry.getValue());
    				sb.append(']');
    			}
    		}
    	}
    	if (sb.length() > 0)
    		sb.append(']');
		req.Items = sb.toString();
		ButlerMailSendResponse rsp = new ButlerMailSendResponse();
		if (req.ZoneId < 0)
			client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
		client.Execute(req, rsp);
		//System.out.println(rsp.ErrMsg);//返回的是对象
        if(rsp.ErrMsg == null) {		
		//插入日志
		L_Email l_email = new L_Email();
		
		//要修改
		l_email.setTitle(email.getTitle());
		l_email.setAnnex(ChangePropName.PropSplice(sb));
		l_email.setReceivedId(email.getUserid());
		l_email.setOpertTime(DateUtil.TimeStamp2Date(DateUtil.getNowTimeStamp()));
		l_email.setOpertAdmin((String)request.getSession().getAttribute("Admintruename"));
		l_email.setZoneId((int)request.getSession().getAttribute("ZoneId"));
		this.l_emailService.insert(l_email);
        }
		return rsp.ErrMsg;
	}
	
	
}
	
